# -*- coding:utf-8 -*-
import urllib2,datetime,traceback,re,random

#检测网络是否通
def check_network(_url="http://www.baidu.com"):
    import urllib2
    try:
        http = urllib2.Http()
        resp, content = http.request(_url)
    except:
        return 0
    return 1

#请求远程数据
def getHttpData(turl):
    try:
        req = urllib2.Request(turl)

        res_data = urllib2.urlopen(req,timeout=4)
        res = res_data.read()
        return  res
    except Exception,e:
        print (datetime.datetime.now(),'getHttpData---',turl)
        #traceback.print_exc()
        return 'err'

#快乐8
#北京福彩网的,http://www.bwlc.net/bulletin/prevkeno.html,http://www.bwlc.net/bulletin/keno.html
'''
<table class="tb" width="100%">
						<tr>
							<th width="10%">期号</th>
							<th width="63%">开奖号码</th>
							<th width="7%">飞盘</th>
							<th width="20%">开奖时间</th>
						</tr>
						<tr class="">
								<td>832507</td>
								<td>17,53,67,10,36,28,79,13,37,19,80,06,23,14,64,41,03,62,33,01</td>
								<td>10</td>
								<td>2017-07-05 15:20</td>
						</tr>
						<tr class="odd">
								<td>832506</td>
								<td>07,76,44,11,02,31,45,04,41,71,09,24,05,79,22,39,08,78,26,36</td>
								<td>04</td>
								<td>2017-07-05 15:15</td>
						</tr>
						</table>
'''
def get_keno8_bjfxw():
    t_url='http://www.bwlc.net/bulletin/keno.html?id=%s'%(random.randint(1,100))
    t_res=getHttpData(t_url)
    if t_res!='err':
        tb_flag='<table class="tb" width="100%">(.+?)</table>'
        tb_re=re.compile(tb_flag,re.S)
        name_regx=tb_re.search(t_res)
        #print name_regx
        if name_regx:#匹配到
            t_groups=name_regx.groups()
            index_obj={0:'id',1:'ball',2:'extra',3:'time'}
            res_data={'ball':[],'extra':[],'id':'','time':''}
            # for ii in name_regx.groups():
            #     print ii
            #group(0)是包含匹配的字符，group(1)则只是()内的
            #正则表达式获取<tr></tr>之间内容
            res_tr = r'<tr.*?>(.*?)</tr>'
            language=name_regx.group(1)
            #print(language)
            m_tr =  re.findall(res_tr,language,re.S|re.M)
            for line in m_tr:
                #print line,line.find('<th')
                #获取表格第一列th 属性
                if line.find('<th')>-1:
                    continue
                    res_th = r'<th.+?>(.*?)</th>'
                    m_th = re.findall(res_th,line,re.S|re.M)
                    for mm in m_th:
                        print unicode(mm,'utf-8'),  #unicode防止乱
                else:#获取表格第二列td 属性值
                    #print('\n----------------')
                    res_td = r'<td>(.*?)</td>'
                    m_td = re.findall(res_td,line,re.S|re.M)
                    ii=0;
                    for nn in m_td:
                        #print unicode(nn,'utf-8')
                        res_data[index_obj[ii]]=nn
                        ii+=1
                    break
            # if res_data['ball'].find(',')>0:#变成数组
            #     res_data['ball']=res_data['ball'].split(',')
            if len(res_data['time'])>0 and res_data['time'].find(':00')<0:
                res_data['time']+=":00"
            #print res_data
            return res_data
            # relink = '<a href=".+?">(.*)</a>'
            # info = '<a href="http://www.baidu.com">baidu</a><br><a href="ssss">ewwew</a>'
            # cinfo = re.findall(relink,info)
            # print(cinfo)
        else:
            print('no match')
            pass
    return  None

#get_keno8_bjfxw()

#百度体彩网的,http://baidu.lecai.com/lottery/draw/view/543
'''
// 最新开奖期的数据
    var latest_draw_result = {"red":["15","38","27","72","65","12","70","48","03","35","68","74","18","54","40","75","26","56","36","80"],"blue":[],"310":[],"extra":["03"],"normal":[]};
    var latest_draw_phase = '832530';
    var latest_draw_time = '2017-07-05 17:15:00';

    var phaseData = {"2017-07-05":{"832433":{"result":{"red":["76","32","50","48","78","35","54","39","79","26","41","36","74","60","18","70","49","16","38","68"],"blue":[],"310":[],"extra":["02"],"normal":[]},"time_draw":"2017-07-05","time_exchange":"2017-09-02","formatSaleAmount":"0","formatPoolAmount":"11,904,985","open_time":"2017-07-05 09:10:00"},"832434":{"result":{"red":["02","46","58","08","56","60","27","43","10","80","42","53","19","70","44","51","18","65","57","31"],"blue":[],"310":[],"extra":["01"],"normal":[]},"time_draw":"2017-07-05","time_exchange":"2017-09-02","formatSaleAmount":"0","formatPoolAmount":"11,904,985","open_time":"2017-07-05 09:15:00"},
'''
def get_keno8_baidu():
    t_url='http://baidu.lecai.com/lottery/draw/view/543?'#id=%s'%(random.randint(1,100))
    t_res=getHttpData(t_url)
    if t_res!='err':
        #号码
        tb_flag='var latest_draw_result =(.+?);'
        tb_re=re.compile(tb_flag,re.S)
        res_regx=tb_re.search(t_res)
        res_data={'ball':[],'extra':[],'id':'','time':''}
        if res_regx:
            tmp_str='data='+res_regx.group(1)
            exec (tmp_str)
            #print(data['red'],data['extra'])
            res_data['ball']=",".join(data['red'])
            res_data['extra']=",".join(data['extra'])

        #期号
        tb_flag='latest_draw_phase =(.+?);'
        tb_re=re.compile(tb_flag,re.S)
        res_regx=tb_re.search(t_res)
        if res_regx:
            tmp_str='data='+res_regx.group(1)
            exec (tmp_str)
            res_data['id']=data
         #时间
        tb_flag='latest_draw_time =(.+?);'
        tb_re=re.compile(tb_flag,re.S)
        res_regx=tb_re.search(t_res)
        if res_regx:
            tmp_str='data='+res_regx.group(1)
            exec (tmp_str)
            res_data['time']=data
        return res_data
    else:
        print('no html')
    return None

def getNewKeno8():
    tmp=get_keno8_bjfxw()
    if not tmp:
        tmp=get_keno8_baidu()
    #print tmp
    return tmp


#获取最大的
def getbig(arr):
    #print len(arr),'--getbig--',arr
    if len(arr)==1:
        return arr[0]
    tmp_val=arr[0]
    n10=tmp_val[0]
    n00=tmp_val[1]
    #print n10,'--n00--',n00
    n_arr=[int(n10),int(n00)]

    tmp_arr=arr+[]
    tmp_arr.remove(tmp_val)
    #print n_arr,'--tmp_arr--',tmp_arr
    for ii in tmp_arr:
        n1=ii[0]
        n0=ii[1]
        cur_arr=[int(n1),int(n0)]
        #print n_arr,'-->',cur_arr
        if n1==n0:#对子
            if n_arr[0]!=n_arr[1]:
                n_arr=cur_arr
            elif cur_arr[0]>n_arr[0]:
                n_arr=cur_arr
        elif n_arr[0]==n_arr[1]:
            continue
        elif sum(cur_arr)%10>sum(n_arr)%10:
            n_arr=cur_arr
        elif sum(cur_arr)%10==sum(n_arr)%10:
            #print n_arr,'-->',cur_arr
            if max(cur_arr)>max(n_arr):
                n_arr=cur_arr
            elif max(cur_arr)==max(n_arr) and cur_arr[0]>n_arr[0]:
                n_arr=cur_arr
            #print n_arr,'-->',cur_arr
    return str(n_arr[0])+str(n_arr[1])

#排序数组
def SortList(arrstr):
    arr=arrstr.split(',')
    new_arr=[]
    while len(arr)>0:
        tnum=getbig(arr)
        #print arr,'--getbig--',tnum
        new_arr.append(tnum)
        arr.remove(tnum)

    return new_arr


#sortList('12,21,26,62,35,65,29,33,77')
#sortList('11,76,33,52,20,71,47,51,14,68,58,30,01,48,59,10,56,62,22,45')
#print getNewKeno8()
#print 'get_keno8_bjfxw>>',get_keno8_bjfxw()
#print 'get_keno8_baidu>>',get_keno8_baidu()



